package com.example.product.interceptor;

import com.example.product.util.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String url = request.getRequestURI();

        // 不拦截登录接口和预检请求（例如：CORS 的 OPTIONS 请求）
        if ("/user/login".equals(url)||"/admin/login".equals(url) || "OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 检查 token 是否存在
        if (token == null) {
            System.out.println("Token 为空，拦截请求");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 返回 401 状态码
            response.getWriter().write("Token is missing");
            return false;
        }

        // 验证 token 是否有效
        TokenUtil tokenUtil = new TokenUtil();
        if (tokenUtil.verifyToken(token)) {
            return true; // Token 验证成功，继续处理请求
        } else {
            System.out.println("Token 无效，拦截请求");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 返回 401 状态码
            response.getWriter().write("Token is invalid or expired");
            return false;
        }
    }
}
